﻿using ModubsRTUTempactureCurve.Base;
using ModubsRTUTempactureCurve.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace ModubsRTUTempactureCurve.Views
{
    /// <summary>
    /// TestSerialWindow.xaml 的交互逻辑
    /// </summary>
    public partial class TestSerialWindow : Window
    {
         
        private SerialPortService _serialService;
        private CancellationTokenSource _monitorCts;
        private bool _isMonitoring = false;

        public ObservableCollection<ItemModel> ItemList { get; set; }

        public TestSerialWindow()
        {
            InitializeComponent();
            InitializeApp();
        }

        private void InitializeApp()
        {
            _serialService = new SerialPortService();
            _serialService.StatusChanged += OnStatusChanged;
            _serialService.ErrorOccurred += OnErrorOccurred;

            ItemList = new ObservableCollection<ItemModel>
        {
            new ItemModel { SlaveId = 1 },
            new ItemModel { SlaveId = 2 }
        };

            dgDevices.ItemsSource = ItemList;

            // 初始化COM口列表
            RefreshPortsList();

            UpdateUIState();
        }

        private void RefreshPortsList()
        {
            var currentSelection = cmbPorts.SelectedItem?.ToString();

            cmbPorts.Items.Clear();
            var ports = SerialPortService.GetAvailablePorts();

            foreach (var port in ports)
            {
                cmbPorts.Items.Add(port);
            }

            // 恢复之前的选择（如果还存在）
            if (!string.IsNullOrEmpty(currentSelection) && ports.Contains(currentSelection))
            {
                cmbPorts.SelectedItem = currentSelection;
            }
            else if (cmbPorts.Items.Count > 0)
            {
                cmbPorts.SelectedIndex = 0;
            }
        }

        private async void btnRefreshPorts_Click(object sender, RoutedEventArgs e)
        {
            RefreshPortsList();
            AddLog("已刷新COM端口列表");
        }

        private async void btnTestPort_Click(object sender, RoutedEventArgs e)
        {
            if (cmbPorts.SelectedItem == null)
            {
                System.Windows.MessageBox.Show("请选择COM端口", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            var portName = cmbPorts.SelectedItem.ToString();
            var baudRate = int.Parse((cmbBaudRate.SelectedItem as ComboBoxItem).Content.ToString());

            try
            {
                btnTestPort.IsEnabled = false;
                btnTestPort.Content = "测试中...";

                var isSuccess = await _serialService.TestPortAsync(portName, baudRate);

                if (isSuccess)
                {
                    AddLog($"测试成功: {portName} 可用");
                    System.Windows.MessageBox.Show($"COM口 {portName} 测试成功！", "测试结果",
                        MessageBoxButton.OK, MessageBoxImage.Information);
                }
                else
                {
                    AddLog($"测试失败: {portName} 无响应");
                    System.Windows.MessageBox.Show($"COM口 {portName} 无响应，请检查设备连接。", "测试结果",
                        MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
            catch (Exception ex)
            {
                AddLog($"测试异常: {ex.Message}");
                System.Windows.MessageBox.Show($"测试过程中发生错误: {ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                btnTestPort.IsEnabled = true;
                btnTestPort.Content = "测试连接";
            }
        }

        private async void cmbPorts_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbPorts.SelectedItem != null && !_isMonitoring)
            {
                var portName = cmbPorts.SelectedItem.ToString();
                var baudRate = int.Parse((cmbBaudRate.SelectedItem as ComboBoxItem).Content.ToString());

                // 自动切换到新选择的端口
                var success = await _serialService.SwitchPortAsync(portName, baudRate);
                if (success)
                {
                    AddLog($"已切换到 {portName}");
                }
            }
        }

        private async void btnStart_Click(object sender, RoutedEventArgs e)
        {
            if (_isMonitoring) return;

            if (cmbPorts.SelectedItem == null)
            {
                System.Windows.MessageBox.Show("请先选择COM端口", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            try
            {
                _isMonitoring = true;
                _monitorCts = new CancellationTokenSource();

                UpdateUIState();
                AddLog("开始监控...");

                // 启动监控任务
                _ = Task.Run(async () => await MonitorLoop(_monitorCts.Token));
            }
            catch (Exception ex)
            {
                AddLog($"启动监控失败: {ex.Message}");
                _isMonitoring = false;
                UpdateUIState();
            }
        }

        private void btnStop_Click(object sender, RoutedEventArgs e)
        {
            StopMonitoring();
        }

        private void btnEmergencyStop_Click(object sender, RoutedEventArgs e)
        {
            AddLog("紧急停止！");
            StopMonitoring();
        }

        private void StopMonitoring()
        {
            _monitorCts?.Cancel();
            _isMonitoring = false;
            UpdateUIState();
            AddLog("监控已停止");
        }

        private async Task MonitorLoop(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested && _isMonitoring)
            {
                try
                {
                    await Task.Delay(1000, cancellationToken);

                    // 这里执行实际的设备读取逻辑
                    foreach (var item in ItemList)
                    {
                        if (cancellationToken.IsCancellationRequested) break;

                        // 模拟读取数据
                        item.Temperature = 25.0 + new Random().NextDouble() * 5;
                        item.Humidity = 50.0 + new Random().NextDouble() * 10;
                    }

                    // 更新UI（通过Dispatcher）
                    await Dispatcher.InvokeAsync(() =>
                    {
                        dgDevices.Items.Refresh();
                    });
                }
                catch (OperationCanceledException)
                {
                    // 正常取消
                    break;
                }
                catch (Exception ex)
                {
                    AddLog($"监控循环错误: {ex.Message}");
                    await Task.Delay(2000, cancellationToken);
                }
            }
        }

        private void UpdateUIState()
        {
            Dispatcher.Invoke(() =>
            {
                btnStart.IsEnabled = !_isMonitoring;
                btnStop.IsEnabled = _isMonitoring;
                btnEmergencyStop.IsEnabled = _isMonitoring;
                cmbPorts.IsEnabled = !_isMonitoring;
                cmbBaudRate.IsEnabled = !_isMonitoring;
                btnRefreshPorts.IsEnabled = !_isMonitoring;
                btnTestPort.IsEnabled = !_isMonitoring;

                txtStatus.Text = _isMonitoring ? "监控中..." : "就绪";
                txtStatus.Foreground = _isMonitoring ? System.Windows.Media.Brushes.Blue : System.Windows.Media.Brushes.Green;
            });
        }

        private void OnStatusChanged(string message)
        {
            Dispatcher.Invoke(() =>
            {
                txtStatus.Text = message;
                AddLog($"状态: {message}");
            });
        }

        private void OnErrorOccurred(string message, bool isCritical)
        {
            Dispatcher.Invoke(() =>
            {
                AddLog($"错误: {message}");
                if (isCritical)
                {
                    System.Windows.MessageBox.Show(message, "严重错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            });
        }

        private void AddLog(string message)
        {
            Dispatcher.Invoke(() =>
            {
                txtLog.AppendText($"{DateTime.Now:HH:mm:ss} - {message}\n");
                txtLog.ScrollToEnd();
            });
        }

        protected override void OnClosed(EventArgs e)
        {
            _monitorCts?.Cancel();
            _serialService?.Dispose();
            base.OnClosed(e);
        }
    }
}
